import React, { useEffect, useState } from "react";
import { Button, Card, Form, Input, message, Modal, Table, Upload } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import {
  reqChangeShopSet,
  reqGetShopSetItem,
  reqGetShopSetList,
  reqRemoveShopSet,
} from "@api/shop/shopSet";
import type { ShopSetItem, ShopSetList } from "@/api/shop/model/shopSetTypes";
import { UploadChangeParam } from "antd/lib/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import { useNavigate } from "react-router-dom";

export default function ShopSet() {
  let columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (x: any, y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      dataIndex: "tmName",
    },
    {
      title: "品牌LOGO",
      dataIndex: "logoUrl",
      render: (text) => <img src={text} className="urlimgs" />,
    },
    {
      title: "操作",
      render: (row: ShopSetItem) => {
        return (
          <div>
            <Button
              icon={<EditOutlined />}
              type="primary"
              className="ml"
              onClick={showModal1(row)}
            >
              修改
            </Button>
            <Button
              className="ml"
              icon={<DeleteOutlined />}
              danger
              type="primary"
              onClick={removeShop(row.id)}
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];

  let [current, setCurrent] = useState(1);
  let [pageSize, setPageSize] = useState(5);
  let [total, setTotal] = useState(100);

  let [shopSetList, setShopSetList] = useState<ShopSetList>([]);

  let getShopList = async (page = current, limit = pageSize) => {
    let result = await reqGetShopSetList({ page, limit });
    setShopSetList(result.records);
    setTotal(result.total);
  };

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [row, setRow] = useState<any>();
  const [rownum, setRownum] = useState<any>();

  //添加对话框
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    form.resetFields();
    // setImageUrl(row.logoUrl);
    setIsModalOpen(true);
    // if (row.id) {
    // form.setFieldsValue({ tmname: row.tmName });

    //   setRowid(row.id)
    // }
  };
  // console.log(row)

  // setRows(row.id)
  // setNumone(0)

  // console.log(row.id)
  // console.log(rows);

  const showModal1 = (row: any) => {
    return () => {
      setRow(row);
      setIsModalOpen(true);
      // form.setFieldsValue({ tmname: row.tmName });
      form.setFieldsValue(row);
      // form.setFieldValue(row)
      setImageUrl(row.logoUrl);
      // console.log(row.logoUrl);
      setRownum(1);
    };
  };

  const handleOk = () => {
    setIsModalOpen(false);
    setRownum(2);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setImageUrl("");
    setRownum(2);
  };

  let [form] = Form.useForm();

  // let changeShop = (row:any) => {
  //   showModal()
  //   form.setFieldsValue({tmname:row.tmName})
  //   setImageUrl(row.logoUrl)
  // }

  const removeShop = (id: number) => {
    return async () => {
      await reqRemoveShopSet(id);
      message.success("删除成功");
      getShopList();
    };
  };
  //添加对话框结束

  //表单

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      // getBase64(info.file.res as RcFile, url => {
      setImageUrl(info.file.response.data);
      setLoading(false);
      // });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const navigate = useNavigate();

  const onFinish = async () => {
    let values = form.getFieldsValue();
    console.log(values);

    if (rownum === 1) {
      let lastvalues = {
        id: row.id,
        tmName: values.tmName,
        logoUrl: imageUrl,
      };
      await reqChangeShopSet(lastvalues);
      message.success("修改成功");
      console.log(row);
      setRow(2);
      setIsModalOpen(false);
      navigate("/syt/shop/shopSet");
      window.location.reload();
    } else {
      let lastvalues = {
        tmName: values.tmName,
        logoUrl: imageUrl,
      };
      await reqGetShopSetItem(lastvalues);
      message.success("添加成功");
      setImageUrl("");
      setRow(2);
      console.log(row);
      setIsModalOpen(false);
      window.location.reload();
    }
  };

  useEffect(() => {
    getShopList();
  }, [current, pageSize]);

  return (
    <Card>
      <Card>
        <Button
          icon={<PlusOutlined />}
          type="primary"
          shape="round"
          onClick={showModal}
        >
          添加
        </Button>
      </Card>

      <Modal
        title="添加品牌"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
        destroyOnClose
        forceRender
      >
        <Form name="basic" onFinish={onFinish} form={form} preserve={false}>
          <Form.Item
            label="品牌名称"
            name="tmName"
            rules={[{ required: true, message: "品牌名称必须写哦" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="logoUrl"
            label="品牌LOGO"
            valuePropName="logoUrl"
            rules={[{ required: true, message: "图片必须添加哦" }]}
            getValueFromEvent={(e) => {
              if (Array.isArray(e)) {
                return e;
              }
              return e && e.fileList;
            }}
            noStyle
          >
            <Upload
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/app-dev/admin/product/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <div style={{ marginTop: 8 }}>上传的图片必须是jpg且不能大于2M</div>
          <Form.Item>
            <Button htmlType="button" onClick={handleCancel} className="ml">
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Card>
        <Table
          columns={columns}
          dataSource={shopSetList}
          bordered
          rowKey="id"
          pagination={{
            total: total,
            pageSize: pageSize,
            current: current,
            showQuickJumper: true,
            pageSizeOptions: [2, 5, 10, 15],
            showSizeChanger: true,
            showTotal: (total) => {
              return <span>共 {total} 条</span>;
            },
            onChange: (page: number, pageSize: number) => {
              setCurrent(page);
              setPageSize(pageSize);
            },
          }}
        />
      </Card>
    </Card>
  );
}
